package com.lang.downloader.http.Interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.ConnectException;

/**
 * 失败重连
 */
public class RetryConnectInterceptor implements Interceptor {

    private final int retryTime;

    public RetryConnectInterceptor(int retryTime) {
        if (retryTime < 0)
            retryTime = Math.abs(retryTime);
        this.retryTime = retryTime;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        for (int time = 0; time <= retryTime; time++) {
            try {
                return chain.proceed(request);
            } catch (Exception e) {
                if (time == retryTime) {
                    throw new ConnectException("链接异常=" + request.url().url());
                }
            }
        }
        throw new ConnectException("链接异常=" + request.url().url());
    }
}
